package com.by.service;// Redis服务类
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    private final StringRedisTemplate redisTemplate;

    public RedisService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //把 Refresh Token 存进 Redis，key 前缀是 refresh_token:
    public void saveRefreshToken(String refreshToken, String userName) {
        redisTemplate.opsForValue().set("refresh_token:" + refreshToken, userName, 5, TimeUnit.MINUTES);
    }
    //检查 Redis 里是否存在这个 Refresh Token
    public boolean isRefreshTokenValid(String refreshToken) {
        return redisTemplate.hasKey("refresh_token:" + refreshToken);
    }
    //删除 Refresh Token。
	//使用场景：退出登录、强制下线、Refresh Token 过期等
    public void deleteRefreshToken(String refreshToken) {
        redisTemplate.delete("refresh_token:" + refreshToken);
    }
	//把 Access Token 加入黑名单。
    public void addToBlacklist(String accessToken, long expirationMs) {
        redisTemplate.opsForValue().set("blacklist:" + accessToken, "invalid", expirationMs, TimeUnit.MILLISECONDS);
    }
	//检查 Access Token 是否在黑名单里。
    public boolean isInBlacklist(String accessToken) {
        return Boolean.TRUE.equals(redisTemplate.hasKey("blacklist:" + accessToken));
    }
}
